package com.bestcem.xm.user.grpc.service;

import cn.hutool.core.lang.ObjectId;
import com.bestcem.bp.xm.user.grpc.v1.services.*;
import com.bestcem.xm.common.core.domain.web.RpcStatusResult;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.enums.ErrorCodeEnum;
import com.bestcem.xm.user.constant.CommonConstant;
import com.bestcem.xm.user.grpc.service.converter.OrgQuotaConverter;
import com.bestcem.xm.user.service.OrganizationQuotainfoService;
import com.bestcem.xm.user.service.dto.PageResponseDTO;
import com.bestcem.xm.user.service.dto.user.OrganizationQuotainfoDTO;
import com.bestcem.xm.user.service.dto.user.QuotaInfoQueryDTO;
import io.grpc.stub.StreamObserver;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.server.service.GrpcService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * 公司限额信息相关服务
 *
 * @author jishuo.yan <jishuo.yan@idiaoyan.com>
 * @version v1.0
 * @date 2022/5/11 17:40
 */
@Slf4j
@GrpcService
public class OrgQuotaInfoGrpcService extends OrgQuotaServiceGrpc.OrgQuotaServiceImplBase {

    @Resource
    private OrganizationQuotainfoService organizationQuotainfoService;

    /**
     * 根据公司id查询公司限额信息
     *
     * @param request
     * @param responseObserver
     * @return void
     * @author zhangfeng <feng.zhang@idiaoyan.com>
     * @date 2022/6/27 14:37
     */
    @Override
    public void getById(GetByIdRequest request, StreamObserver<GetByIdResponse> responseObserver) {
        GetByIdResponse.Builder builder = GetByIdResponse.newBuilder();
        String id = request.getId();
        String errMsg = "";
        if (!ObjectId.isValid(id)) {
            errMsg = String.format(CommonConstant.ERROR_MSG_FORMATTER, ErrorCodeEnum.PARAM_ERROR.getMsg(), "ID为空或格式不对");
            builder.setStatus(RpcStatusResult.error(errMsg));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }
        OrganizationQuotainfoDTO orgDTO = new OrganizationQuotainfoDTO();
        orgDTO.setQuotainfoId(id);
        // 获取统计数据
        ServiceResult<List<OrganizationQuotainfoDTO>> serviceResult = organizationQuotainfoService.selectBySelective(orgDTO);

        // 返回数据
        if (!CollectionUtils.isEmpty(serviceResult.getData())) {
            Quota quota = OrgQuotaConverter.organizationQuotainfoDtoToQuotaInfo(serviceResult.getData().get(0));
            builder.setQuota(quota);
            builder.setStatus(RpcStatusResult.success());
        } else {
            errMsg = String.format(CommonConstant.ERROR_MSG_FORMATTER, ErrorCodeEnum.SYSTEM_ERROR.getMsg(),
                    String.format("对应的机构限额信息不存在 id:%s", id));
            builder.setStatus(RpcStatusResult.error(errMsg));
        }

        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 根据搜索条件分页查询公司限额信息
     *
     * @param request
     * @param responseObserver
     * @return void
     * @author zhangfeng <feng.zhang@idiaoyan.com>
     * @date 2022/6/27 15:39
     */
    @Override
    public void listQuotasByPage(ListQuotasByPageRequest request, StreamObserver<ListQuotasByPageResponse> responseObserver) {
        ListQuotasByPageResponse.Builder builder = ListQuotasByPageResponse.newBuilder();
        QuotaInfoQueryDTO quotaInfoQueryDTO = OrgQuotaConverter.platformQuotaQueryToQuotaInfoQueryDTO(request.getQuery());
        String errMsg = "";
        if (!request.hasPage()) {
            errMsg = "分页参数不能为空";
        }
        if (StringUtils.isNotEmpty(errMsg)) {
            errMsg = String.format(CommonConstant.ERROR_MSG_FORMATTER, ErrorCodeEnum.PARAM_ERROR.getMsg(), errMsg);
            builder.setStatus(RpcStatusResult.error(errMsg));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }
        quotaInfoQueryDTO.setPage(request.getPage().getPage());
        quotaInfoQueryDTO.setPerPage(request.getPage().getSize());

        ServiceResult<PageResponseDTO<OrganizationQuotainfoDTO>> result =
                organizationQuotainfoService.listPageByQuotaInfo(quotaInfoQueryDTO);
        if (result.isSuccess()) {
            builder.addAllQuotas(OrgQuotaConverter.organizationQuotainfosDtoToQuotaInfos(result.getData().getRows()));
            builder.setTotal(result.getData().getTotal().intValue());
            builder.setStatus(RpcStatusResult.success());
        } else {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
        }

        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 创建公司限额信息
     *
     * @param request
     * @return responseObserver
     * @author yanjishuo <jishuo.yan@idiaoyan.cn>
     * @author yun.pan <yun.pan@idiaoyan.cn>
     * @date 2022/05/11 16:22
     */
    @Override
    public void createQuota(CreateQuotaRequest request, StreamObserver<CreateQuotaResponse> responseObserver) {
        CreateQuotaResponse.Builder builder = CreateQuotaResponse.newBuilder();
        if (!request.hasParam()) {
            String errMsg = String.format(CommonConstant.ERROR_MSG_FORMATTER, ErrorCodeEnum.PARAM_ERROR.getMsg(), "限额信息不能为空");
            builder.setStatus(RpcStatusResult.error(errMsg));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }
        OrganizationQuotainfoDTO orgQuotainfoDTO = OrgQuotaConverter.quotaCreateParamToDto(request.getParam());
        ServiceResult<OrganizationQuotainfoDTO> byOrgId = organizationQuotainfoService.getByOrgId(orgQuotainfoDTO.getOrgId());
        if (Objects.nonNull(byOrgId.getData())) {
            builder.setId(byOrgId.getData().getQuotainfoId());
            builder.setStatus(RpcStatusResult.success());
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }
        ServiceResult<String> result = organizationQuotainfoService.insertSelective(orgQuotainfoDTO);
        if (result.isSuccess()) {
            builder.setId(result.getData());
            builder.setStatus(RpcStatusResult.success());
        } else {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 更新公司限额信息
     *
     * @param request
     * @return responseObserver
     * @author yanjishuo <jishuo.yan@idiaoyan.cn>
     * @author yun.pan <yun.pan@idiaoyan.cn>
     * @date 2022/05/11 17:22
     */
    @Override
    public void updateQuota(UpdateQuotaRequest request, StreamObserver<UpdateQuotaResponse> responseObserver) {
        UpdateQuotaResponse.Builder builder = UpdateQuotaResponse.newBuilder();
        if (!request.hasParam()) {
            String errMsg = String.format(CommonConstant.ERROR_MSG_FORMATTER, ErrorCodeEnum.PARAM_ERROR.getMsg(), "限额信息不能为空");
            builder.setStatus(RpcStatusResult.error(errMsg));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }
        OrganizationQuotainfoDTO orgQuotainfoDTO = OrgQuotaConverter.quotaUpdateParamToDto(request.getParam());
        String quotaInfoId = request.getId();
        orgQuotainfoDTO.setQuotainfoId(quotaInfoId);
        // 更新公司限额信息
        ServiceResult<Integer> result = organizationQuotainfoService.updateByPrimaryKeySelective(orgQuotainfoDTO);
        if (result.isSuccess()) {
            builder.setId(quotaInfoId);
            builder.setStatus(RpcStatusResult.success());
        } else {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 根据搜素条件查询公司限额信息
     *
     * @param request
     * @return responseObserver
     * @author yanjishuo <jishuo.yan@idiaoyan.cn>
     * @author yun.pan <yun.pan@idiaoyan.cn>
     * @date 2022/05/11 18:22
     */
    @Override
    public void listQuotas(ListQuotasRequest request, StreamObserver<ListQuotasResponse> responseObserver) {
        ListQuotasResponse.Builder builder = ListQuotasResponse.newBuilder();
        OrganizationQuotainfoDTO orgQuotainfoDTO = OrgQuotaConverter.quotaQueryParamToDto(request.getParam());
        // 根据条件获取公司限额信息列表
        ServiceResult<List<OrganizationQuotainfoDTO>> result = organizationQuotainfoService.selectBySelective(orgQuotainfoDTO);
        if (result.isSuccess()) {
            //查询成功
            builder.setStatus(RpcStatusResult.success());
            builder.addAllQuotas(OrgQuotaConverter.organizationQuotainfosDtoToQuotaInfos(result.getData()));
        } else {
            //查询失败
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }
}

